// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
// 加载服务
// 加载全局错误码
const { UniCloudError, isUniPayError, ERROR } = require('./common/error');
const service = require('./service');
const db = uniCloud.database();
const _ = db.command;

const getZoneTime = (offset)=> {
    // 取本地时间
    let localtime = new Date();
    // 取本地毫秒数
    let localmesc = localtime.getTime();
    // 取本地时区与格林尼治所在时区的偏差毫秒数
    let localOffset = localtime.getTimezoneOffset() * 60000;
    // 反推得到格林尼治时间
    let utc = localOffset + localmesc;
    // 得到指定时区时间
    let calctime = utc + (3600000 * offset);
    return new Date(calctime);
};


module.exports = {
	_before: function () { // 通用预处理器

	},
	/**
	 * 中间件（请求后执行）
	 */
	_after(error, result) {
		if (error) {
			if (error.errCode) {
				let errCode = error.errCode
				if (!isUniPayError(errCode)) {
					// 如果不是插件预设的错误码，则原样返回错误信息
					return error;
				}
				// return new UniCloudError({
				// 	code: errCode,
				// 	message: error.errMsg || this.t(errCode, error.errMsgValue),
				// });
			}
			throw error
		}
		return result;
	},
	ceshi:async ()=>{
		let time = new Date(new Date().setHours(0,0,0,0))*1//获取当天0点时间戳
		console.log("time====>>>",time);
		let getOrderRes = await db.collection("wolf-tixian").where({
			type:0,
			status:0,
			batch_status:_.or(_.eq(''),_.eq(null),_.eq(undefined)),
			create_time:_.lte(time)
		}).field({
			con_price:true,
			openid:true,
			name:true,
			out_batch_no:true,
			order_id:true,
			_id:true
		}).limit(10).get()
		console.log(getOrderRes);
		if(getOrderRes.data.length > 0){
			for(let i=0;i<getOrderRes.data.length;i++){
				let item = getOrderRes.data[i]
				// let cBatchRes = await service.batches.createBatch(item)
				// console.log("cBatchRes=====++++++----->>>>>>",cBatchRes);
				// if(cBatchRes.statusCodeValue == 200){
				// 	let obj = {
				// 		batch_status:cBatchRes.body.batch_status,
				// 		original_data:cBatchRes.body
				// 	}
				// 	await db.collection('wolf-tixian').doc(item._id).update(obj)
				// }
			}
		}
	},
	/**
	 * 定时任务
	 */
	_timing:async ()=>{
	// ceshi:async ()=>{
		//查询 自动提现，tpye==0,已发起提现 ，还未 没有成功，关闭，失败，订单
		//发起提现
		let date = getZoneTime(8)//获取8时区的时间
		let nowHours = date.getHours()
		// let time1 = new Date(date.setHours(0,0,0,0))*1
		let time1 = new Date(new Date().toDateString()).getTime()
		// let date = new Date()
		// let nowHours = date.getHours()//获取当前时间点
		
		console.log("========>>>>",nowHours,time1);
		//在seveless 上是0时区，时间需要加上8
		// nowHours += 8
		console.log("nowHours==> ",nowHours,nowHours>=14 && nowHours<=18);
		if(nowHours>=14 && nowHours<=20){//每天下午的2-8点
			let time = new Date(new Date().setHours(0,0,0,0))*1//获取当天0点时间戳
			console.log("time====>>>",time);
			let getOrderRes = await db.collection("wolf-tixian").where({
				type:0,
				status:0,
				batch_status:_.or(_.eq(''),_.eq(null),_.eq(undefined)),
				create_time:_.lte(time)
			}).field({
				con_price:true,
				openid:true,
				name:true,
				out_batch_no:true,
				order_id:true,
				_id:true
			}).limit(10).get()
			console.log("getOrderRes=====---------->>>>>>",getOrderRes);
			if(getOrderRes.data.length > 0){
				for(let i=0;i<getOrderRes.data.length;i++){
					let item = getOrderRes.data[i]
					let cBatchRes = await service.batches.createBatch(item)
					console.log("cBatchRes=====++++++----->>>>>>",cBatchRes);
					if(cBatchRes.statusCodeValue == 200){
						let obj = {
							batch_status:cBatchRes.body.batch_status,
							original_data:cBatchRes.body
						}
						await db.collection('wolf-tixian').doc(item._id).update(obj)
					}
				}
			}
		}
		
		
		let res = await db.collection("wolf-tixian").where({
			type:0,
			status:0,
			batch_status:_.and(_.neq("SUCCESS"),_.neq("CLOSED"),_.neq("FAIL"),_.neq("")),
		}).field({
			out_batch_no:true,
			order_id:true,
			_id:true
		}).limit(10).get()
		console.log("res=====----------->>>>>>>>>",res,res.data.length);
		if(res.data.length > 0){
			for(let i=0;i<res.data.length;i++){
				let item = res.data[i]
				let data = {
					out_batch_no:item.out_batch_no,
					out_detail_no:item.order_id
				}
				let getRes = await service.batches.getBatchOrder(data)//发起查询
				console.log("getRes=====>>>>>>>>>",getRes);
				if(getRes.status==200){
					let obj = {
						batch_status:getRes.data.detail_status,
						original_data:getRes.data
					}
					if(obj.batch_status==="SUCCESS"){
						obj.status = 1//提现完成
						obj.update_time = new Date().getTime()
					}
					await db.collection('wolf-tixian').doc(item._id).update(obj)
				}
			}
		}
		
		
		
	},
	
	
	/**
	 * 创建提现订单，
	 * @param {object} 提现订单信息
	 * @return {object} 此笔提现的微信返回的全部信息
	 */
   async createBatch(data) {
		// console.log("createBatch===>",await service.batches.createBatch(data))
		  // service.batches.createBatch(data) //返回结果
		// "body": {
		// 	"batch_id": "131000710102101745919402023113008885004060",
		// 	"batch_status": "ACCEPTED",
		// 	"create_time": "2023-11-30T13:20:40+08:00",
		// 	"out_batch_no": "TX6111881700808695956x1"
		// },
		// "statusCode": "OK",
		// "statusCodeValue": 200 
		return await service.batches.createBatch(data)
   },
   /**
   	 * 通过商家明细单号查询提现状态，
   	 * @param {object} data.out_detail_no  【商家明细单号】 商户系统内部区分转账批次单下不同转账明细单的唯一标识
	 * @@param {object} data.out_batch_no 【商家批次单号】 商户系统内部的商家批次单号，在商户系统内部唯一
   	 * @return {object} 此次查询微信返回的结果
   	 */
   async getBatchOrder(data) {
		//service.batches.getBatchOrder(data) 微信返回结果
		// "data": {
		// 	"appid": "wx6b34f49770eedb67",
		// 	"batch_id": "131000710102101745919402023113008885004060",
		// 	"detail_id": "132000710102101745919402023113054994503596",
		// 	"detail_status": "WAIT_PAY",
		// 	"mchid": "1647923460",
		// 	"openid": "oNfZq5fUaHEE_2h-r5M0p9_cGce8",
		// 	"out_batch_no": "TX6111881700808695956x1",
		// 	"out_detail_no": "TX6111881700808695955",
		// 	"transfer_amount": 38,
		// 	"transfer_remark": "用户提现",
		// 	"update_time": "2023-11-30T13:20:46+08:00"
		// },
		// "status": 200,
		
		
   		return await service.batches.getBatchOrder(data)
   },
}
